<?php
namespace Common\Lib\User;

use Think\Exception;
use Think\Model;
use Think\StaticRouteAppID;

class UserHelper{
    const IS_VALIDATE_PASSWORD = false;//是否验证密码

    const ADMIN_NAME = 'admin';//管理员
    const TYPE_ADD = 'add';//新增
    const TYPE_EDIT = 'edit';//编辑

    const SEX_MALE = 1;//男
    const SEX_FEMALE = 2;//女

    const LENGTH_MIN_USER_NAME = 5;//用户名最大小度限制
    const LENGTH_MAX_USER_NAME = 20;//用户名最大长度限制
    const LENGTH_MAX_TRUE_NAME = 15;//姓名最大长度限制
    const LENGTH_MAX_ADDRESS = 150;//地址最大长度限制
    const LENGTH_MAX_EMAIL = 50;//邮箱最大长度限制
    const LENGTH_MAX_ALIPAYID = 30;//支付宝账号最大长度限制
    const LENGTH_MAX_WXPAYID = 30;//微信账号最大长度限制
    const LENGTH_MAX_BANKNAME = 60;//开户银行最大长度限制
    const LENGTH_MAX_BANKOPENCITY = 30;//银行开户城市
    const LENGTH_MAX_BANKNO = 30;//银行账号最大长度限制
    const LENGTH_MAX_REMARK = 2048;//备注最大长度限制


    const REG_PASSWORD = "/^[a-zA-Z]\w{5,17}$/";
    const REG_PHONE = "/^1[34578]\d{9}$/";
    const REG_BIRTHDAY = "/^\d{4}[\-](0?[1-9]|1[012])[\-](0?[1-9]|[12][0-9]|3[01])$/";
    const REG_EMAIL = "/^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/";
    const REG_ID_CARD = "/^(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)$/";
    const REG_BANK_NO = "/^([1-9]{1})(\d{15}|\d{18})$/";

    /**
     * 验证与获取用户信息
     * @param $data
     * @param $type
     * @return array
     * @throws UserInfoException
     */
    public static function getUserInfo($data,$type = self::TYPE_EDIT){
        $user = [];

        if($type === self::TYPE_ADD){
            //用户名UserName
            if(isset($data['UserName']) && strlen($data['UserName']) > 0 ){
                if(strlen($data['UserName']) > self::LENGTH_MAX_USER_NAME){
                    throw new UserInfoException("用户名过长！");
                }
                /*
                if(strlen($data['UserName']) < self::LENGTH_MIN_USER_NAME){
                    throw new UserInfoException("用户名不能小于5个字符！");
                }
                */
                if($type === self::TYPE_ADD){
                    if(M('User')->where('UserName=\''.$data['UserName'].'\'')->count() > 0){
                        throw new UserInfoException('该用户名已存在');
                    }
                }else{
                    $oldUser = M('User')->find($data['ID']);
                    if($oldUser['UserName'] !== $data['UserName']){
                        if(M('User')->where('UserName=\''.$data['UserName'].'\'')->count() > 0){
                            throw new UserInfoException('该用户名已存在');
                        }
                    }
                }
                $user['UserName'] = $data['UserName'];
            }else{
                throw new UserInfoException('用户名不能为空！');
            }

            //添加时间AddTime
            $user['AddTime'] = date('Y-m-d H:i:s');
        }else{
            $user['ID'] = $data['ID'];
        }


        //姓名:不能为空
        if(isset($data['TrueName']) && strlen($data['TrueName']) > 0 ){
            if(mb_strlen($data['TrueName'],"utf-8") > self::LENGTH_MAX_TRUE_NAME){
                throw new UserInfoException("姓名过长！");
            }
            $user['TrueName'] = $data['TrueName'];
        }else{
            $user['TrueName'] = $data['UserName'];
        }

        //密码Password
        if(isset($data['Password']) && strlen($data['Password']) > 0 ){
            if(self::IS_VALIDATE_PASSWORD && !preg_match(self::REG_PASSWORD,$data['Password'])){
                throw new UserInfoException('密码格式错误');
            }
            if(!isset($data['UserName'])){
                throw new UserInfoException('密码设置错误');
            }else{
                $user['Password'] = sp_password($data['Password'],'',$data['UserName']);
            }
        }else{
            if($type === self::TYPE_ADD){
                throw new UserInfoException('密码不能为空！');
            }
        }

        //性别:不能为空|[1|2]
        if(isset($data['Sex']) && strlen($data['Sex']) > 0 ){
            if(intval($data['Sex']) !==self::SEX_MALE && intval($data['Sex']) !== self::SEX_FEMALE){
                throw new UserInfoException('性别格式错误');
            }
            $user['Sex'] = $data['Sex'];
        }else{
            $user['Sex'] = self::SEX_MALE;
            //throw new UserInfoException('性别不能为空');
        }

        //出生年月
        if(isset($data['Birthday'])){
            if(strlen($data['Birthday']) > 0){
                if(!preg_match(self::REG_BIRTHDAY,$data['Birthday'])){
                    throw new UserInfoException('出生年月格式错误');
                }
            }else{
                $data['Birthday'] = null;
            }
            $user['Birthday'] = $data['Birthday'];
        }

        //所在城市
        if(isset($data['City'])){
            if(mb_strlen($data['City'],"utf-8") > self::LENGTH_MAX_ADDRESS){
                throw new UserInfoException("所在城市过长！");
            }
            $user['City'] = $data['City'];
        }

        //联系地址Address
        if(isset($data['Address'])){
            if(mb_strlen($data['Address'],"utf-8") > self::LENGTH_MAX_ADDRESS){
                throw new UserInfoException("联系地址过长！");
            }
            $user['Address'] = $data['Address'];
        }

        //手机号:不能为空|手机号格式|唯一性
        if(isset($data['Phone']) && strlen($data['Phone']) > 0 ){
            if(!preg_match(self::REG_PHONE,$data['Phone'])){
                throw new UserInfoException('手机号格式错误');
            }

            if($type === self::TYPE_ADD){
                if(M('User')->where('Phone='.$data['Phone'])->count() > 0){
                    throw new UserInfoException('该手机号已存在');
                }
            }else{
                $oldUser = M('User')->find($data['ID']);
                if($oldUser['Phone'] !== $data['Phone']){
                    if(M('User')->where('Phone='.$data['Phone'])->count() > 0){
                        throw new UserInfoException('该手机号已存在');
                    }
                }
            }
            $user['Phone'] = $data['Phone'];
        }else{
            throw new UserInfoException('手机号不能为空');
        }

        //邮箱:邮箱格式
        if(isset($data['EMail'])){
            if(strlen($data['EMail']) > 0 ){
                if(!preg_match(self::REG_EMAIL,$data['EMail'])){
                    throw new UserInfoException('邮箱格式错误');
                }
                if(strlen($data['EMail']) >  self::LENGTH_MAX_EMAIL){
                    throw new UserInfoException('邮箱地址过长');
                }
            }
            $user['EMail'] = $data['EMail'];
        }

        //身份证:格式
        if(isset($data['CardNO']) && strlen($data['CardNO']) > 0){
            if(!preg_match(self::REG_ID_CARD,$data['CardNO'])){
                throw new UserInfoException('身份证格式错误');
            }
            $user['CardNO'] = $data['CardNO'];
        }

        if(isset($data['OrderNO']) && strlen($data['OrderNO']) > 0){
            $user['OrderNO'] = $data['OrderNO'];
        }

        //用户编号
        //身份证前两位+5位编号
        if($type === self::TYPE_ADD){
            if(isset($data['CardNO']) && strlen($data['CardNO']) > 0){
                $user['UserNO'] = self::getUserNOByCardNO($user['CardNO']);
            }
        }else{
            $oldUser = M('User')->find($data['ID']);
            if(substr($oldUser['CardNO'],0,2) !== substr($user['CardNO'],0,2)){
                $user['UserNO'] = self::getUserNOByCardNO($user['CardNO']);
            }else{
                $user['UserNO'] = $oldUser['UserNO'];
            }
        }

        //更新时间
        $user['UpdateTime'] = date('Y-m-d H:i:s');
        //备注Remarks
        if(isset($data['Remarks'])){
            if(mb_strlen($data['Remarks'],"utf-8") > self::LENGTH_MAX_REMARK){
                throw new UserInfoException("备注过长！");
            }
            $user['Remarks'] = $data['Remarks'];
        }
        if(isset($data['QQOpenID'])){
            $user['QQOpenID'] = $data['QQOpenID'];
        }
        if(isset($data['WXOpenID'])){
            $user['WXOpenID'] = $data['WXOpenID'];
        }
        if(isset($data['WXUnionID'])){
            $user['WXUnionID'] = $data['WXUnionID'];
        }

        return $user;
    }
    /**
     * 添加用户
     * @param $data
     * @return int|bool
     * @throws UserInfoException
     */
    public static function add($data){
        $model = new Model();
        $model->startTrans();
        try{
            $user = self::getUserInfo($data,self::TYPE_ADD);
            $userId = M('User')->add($user);
            if($userId){
                $model->commit();
                return $userId;
            }else{
                $model->rollback();
                return false;
            }
            //return M('User')->add($user);
        } catch (UserInfoException $exception){
            $model->rollback();
            throw $exception;
        }catch (Exception $exception){
            $model->rollback();
            throw $exception;
            //throw new UserInfoException('数据库验证失败');
        }
    }
    /**
     * 编辑用户信息
     * @param $data
     * @return int|bool
     * @throws UserInfoException
     */
    public static function edit($data){
        try{
            $user = self::getUserInfo($data);
            return M('User')->save($user);
        } catch (Exception $exception){
            throw new UserInfoException($exception->getMessage());
        }
    }

    /**
     * @param $id
     * @return bool
     * @throws UserInfoException
     */
    public static function delete($id){
        return M('User')->where(array('ID'=>$id))->save(array('IsDel'=>1));
    }

    /**
     * 根据用户身份证号获取用户编号
     * @param $CardNO
     * @return int|string
     */
    public static function getUserNOByCardNO($CardNO){
        $number = '';
        $number_pre = substr($CardNO,0,2);
        $where['UserNO'] = array('like',$number_pre.'%');
        $number_sub = M('User')->where($where)->max('UserNO');
        if($number_sub){
            $number = intval($number_sub) + 1;
        }else{
            $number = $number_pre.'00001';
        }
        return $number;
    }
}